<script lang="ts">
import { defineComponent, ref, watch } from "vue"
import { RouterModule } from "@/store/modules/router";
import { UserModule } from "@/store/modules/user";
import { Erc20Module } from "@/store/modules/erc20";
import { useI18n } from "vue-i18n";
import { toStringMatch, fromWei, toWei } from "@/utils/format";
import { USDT_TOKEN, AIBOT_TOKEN, router_CONTRACT } from "@/contract";
import { showToast, showDialog, showConfirmDialog } from 'vant';
import { BigNumber } from "bignumber.js";
import { getAssetsFile } from "@/utils/pub-use";
import { debounce } from "@/utils/debounce.js";



export default defineComponent({
    setup() {
        const { t } = useI18n();
        const active = ref(0)
        const amount = ref()
        const pageLoading = ref(true)
        const amountsOut = ref([]);
        const isSwapDisabled = ref(false);
        const USDT = ref()
        const AIBOT = ref()
        const loading = ref(false)
        const fromItem = ref({
            icon: getAssetsFile("USDT.svg"),
            name: "USDT",
            price: 0,
            amount: 0,
            TOKEN: USDT_TOKEN
        });
        const toItem = ref({
            icon: getAssetsFile("logo.png"),
            name: "AIBOT",
            price: 0,
            amount: 0,
            TOKEN: AIBOT_TOKEN
        });
        const swapToFrom = () => {
            if (pageLoading.value) return
            let swapItem;
            swapItem = fromItem.value;
            fromItem.value = toItem.value;
            toItem.value = swapItem;
            updateModelValue(amount.value)
        };
        const temp = debounce(handleSearch, 500);
        const updateModelValue = (query: string) => {
            if (query) {
                isSwapDisabled.value = true;
                temp();
            }
        };
        function handleSearch() {
            if (amount.value) {
                RouterModule.getAmountsOut({ amount: amount.value, fromTOKEN: fromItem.value.TOKEN, toTOKEN: toItem.value.TOKEN }).then((res) => {
                    amountsOut.value = res;
                    isSwapDisabled.value = false;
                });
            }
        }
        const loadData = async () => {
            let usdt: string = await Erc20Module.balanceOf({
                owner: USDT_TOKEN,
            });
            USDT.value = fromWei(usdt);
            let aibot: string = await Erc20Module.balanceOf({
                owner: AIBOT_TOKEN,
            });
            AIBOT.value = fromWei(aibot);
            if (fromItem.value.name == 'USDT') {
                fromItem.value.amount = USDT.value
                toItem.value.amount = AIBOT.value
            } else {
                fromItem.value.amount = AIBOT.value
                toItem.value.amount = USDT.value
            }
            pageLoading.value = false
        }
        const sendSwapExactTokensForTokens = async () => {
            loading.value = true;
            try {
                if (Number(fromItem.value.amount) < Number(amount.value)) {
                    showToast(t("layout.theBalanceAIBOTIsOnly") + USDT.value);
                    loading.value = false;
                    return;
                }
                const allowance = await Erc20Module.allowance({
                    owner: fromItem.value.TOKEN,
                    spender: router_CONTRACT,
                });
                if (new BigNumber(allowance).lte(toWei(amount.value))) {
                    await Erc20Module.approve({
                        owner: fromItem.value.TOKEN,
                        spender: router_CONTRACT,
                    });
                }
                await RouterModule.swapExactTokensForTokensSupportingFeeOnTransferTokens({
                    amountIn: amountsOut.value[0],
                    amountOutMin: toWei(fromWei(amountsOut.value[1]) * 0.9),
                    fromTOKEN: fromItem.value.TOKEN,
                    toTOKEN: toItem.value.TOKEN
                });
                showDialog({
                    title: t("layout.success"),
                }).then(() => { });
                loadData();
            } catch (error) {
                console.log(error)
            }
            loading.value = false;
        };
        watch(
            () => UserModule.userAddr,
            (newUserAddr: string) => {
                if (newUserAddr) {
                    loadData();
                }
            },
            { immediate: true }
        );
        return {
            active,
            amount,
            amountsOut,
            pageLoading,
            USDT,
            loading,
            isSwapDisabled,
            fromItem,
            toItem,
            swapToFrom,
            fromWei,
            updateModelValue,
            sendSwapExactTokensForTokens
        }
    }
})
</script>

<template>
    <div class="page">
        <van-tabs v-model:active="active">
            <div class="heads">
                <div class="name">
                    {{ $t('layout.exchange') }}
                    <span>{{ $t('layout.Tradetokensinstantly') }}</span>
                </div>
                <div class="right-icon">
                    <!-- <img src="@/assets/image/image13.png" alt="" srcset="">
                    <img src="@/assets/image/image14.png" alt="" srcset=""> -->
                </div>
            </div>
            <van-tab :title="$t('layout.exchange')"></van-tab>
            <van-tab :title="$t('layout.fluidity')"></van-tab>
            <div class="from">
                <div class="from-item">
                    <div class="name">From <span>{{ fromItem.amount }} {{ $t('layout.balance') }}</span></div>
                    <div class="row">
                        <div class="name-info">
                            <img :src="fromItem.icon" alt="" srcset="">
                            <span>{{ fromItem.name }}</span>
                            <!-- <van-icon name="play" /> -->
                        </div>
                        <van-field v-model="amount" type="number" @update:model-value="updateModelValue"
                            :placeholder="$t('layout.PleaseentertheUSDTquantity')" />
                    </div>
                </div>
                <div class="swap-icon" @click="swapToFrom"></div>
                <div class="to-item">
                    <div class="name">From <span>{{ toItem.amount }} {{ $t('layout.balance') }}</span></div>
                    <div class="row">
                        <div class="name-info">
                            <img :src="toItem.icon" alt="" srcset="">
                            <span>{{ toItem.name }}</span>
                            <!-- <van-icon name="play" /> -->
                        </div>
                        <div class="to-amount">{{ fromWei(amountsOut[1] || 0) }}</div>
                    </div>
                </div>
                <van-button type="primary" :disabled="pageLoading || isSwapDisabled" :loading="loading"
                    @click="sendSwapExactTokensForTokens">{{
                        $t('layout.exchange') }}</van-button>
            </div>
        </van-tabs>
    </div>
</template>

<style lang="less" scoped>
.page {
    padding: 0 15px 15px 15px;

    .van-tabs {

        &:deep(.van-tabs__wrap) {
            display: none;
            border-radius: 8px;
            border: 1px solid rgba(255, 255, 255, 0.1);

            .van-tabs__nav {
                background: linear-gradient(124deg, #01012B 0%, rgba(50, 67, 123, 0) 100%);

                .van-tab {
                    font-size: 16px;
                    font-weight: 500;
                    color: #FFFFFF;

                    &.van-tab--active {
                        background: linear-gradient(90deg, #01012B 0%, #32437B 100%);
                        border-radius: 8px;
                    }
                }

                .van-tabs__line {
                    display: none;
                }

            }
        }

        .heads {
            margin-top: 30px;
            display: flex;
            align-items: center;
            justify-content: space-between;

            .name {
                font-size: 18px;
                font-weight: bold;
                color: #FFFFFF;

                span {
                    margin-top: 8px;
                    display: block;
                    font-size: 12px;
                    font-weight: 400;
                    color: #FFDBC4;
                    opacity: .5;
                }
            }

            .right-icon {
                img {
                    margin-left: 15px;
                    height: 12px;
                }
            }
        }

        .swap-icon {
            width: 30px;
            height: 30px;
            position: absolute;
            left: 0;
            right: 0;
            margin: 0 auto;
        }

        .from {
            margin-top: 20px;

            .from-item,
            .to-item {
                padding: 20px 15px;
                background: linear-gradient(180deg, #313669 0%, rgba(118, 113, 171, 0) 100%);
                border-radius: 8px 8px 0 0;

                .name {
                    display: flex;
                    justify-content: space-between;

                    span {
                        color: #FFBD91;
                    }
                }

                .row {
                    margin-top: 15px;
                    display: flex;
                    justify-content: space-between;
                    align-items: center;

                    .name-info {
                        display: flex;
                        align-items: center;

                        img {
                            width: 30px;
                        }

                        span {
                            margin: 0 8px 0 12px;
                        }

                        .van-icon {
                            transform: rotate(90deg);
                        }
                    }

                    .van-field {
                        background: transparent;
                        border-radius: 8px;
                        padding: 15px 0;

                        &:deep(input) {
                            color: #fff;
                            text-align: right;
                        }

                        &::after {
                            display: none
                        }
                    }
                }
            }

            .to-item {
                height: 150px;
                padding: 40px 15px 20px 15px;
                box-sizing: border-box;
                background: url("@/assets/image/image15.png") center/contain no-repeat;
            }
        }
    }

    .van-button {
        margin-top: 15px;
    }
}
</style>
../../utils/debounce.js